package com.lilicould.controller;

import com.google.gson.Gson;
import com.lilicould.entity.Courses;
import com.lilicould.service.CourseService;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/course/*")
public class CourseController extends BaseServlet{
    public void listAll(HttpServletRequest  req, HttpServletResponse resp) throws IOException {
        resp.setContentType("json/application;charset=utf-8");

        // 获取所有课程
        String result = new CourseService().getAllCourses();

        // 如果数据不为空，说明成功拿到数据
        if (result != null) {
            resp.setStatus(HttpServletResponse.SC_OK);
            PrintWriter out = resp.getWriter();
            out.print(result);
        }else {
            // 数据为空，说明没有数据
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    public void add(HttpServletRequest  req, HttpServletResponse resp) throws IOException {
        resp.setContentType("json/application;charset=utf-8");

        // 获取课程信息
        Courses course = new Gson().fromJson(req.getReader(), Courses.class);

        // 添加课程
        String result = new CourseService().addCourse(course);

        // 若非空，说明存在错误信息，返回400状态码和错误信息
        if (result != null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            PrintWriter out = resp.getWriter();
            out.print(result);
        }else {
            // 添加成功，返回200状态码
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    }

    public void delete(HttpServletRequest  req, HttpServletResponse resp) throws IOException {
        resp.setContentType("json/application;charset=utf-8");
        // 获取课程id
        String courseId = req.getParameter("courseId");
        // 删除课程并且返回结果
        String result = new CourseService().deleteCourse(courseId);

        if (result != null) {
            // 若不为空，说明存在错误信息，返回400状态码和错误信息
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().print(result);
        } else {
            // 删除成功，返回200状态码
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    }
}
